<template>
  <el-card class="el-card--has-heading success">
    <div slot="header" class="v-card__headerInner">
      <p>banner配置</p>
      <transition name="el-zoom-in-center">
        <div v-show="showTip">
          <p class="v-card__header-tip">单击图片可预览大图</p>
        </div>
      </transition>
      <el-button
        class="v-card__headerAction"
        type="text"
        @click="onClickCreate"
        v-auth:[$P.business.banners.create]
      >创建banner图</el-button>
    </div>
    <v-table
      :dataSource="dataSource"
      :columns="filterColumn(columns,[$P.business.banners.update,$P.business.banners.delete])"
      :loading="loading"
      :total="total"
      v-bind="bindProps"
      v-on="bindListeners"
    ></v-table>

    <Modal
      :title="modalTitle"
      :loading="modalLoading"
      :visible.sync="visible"
      :width="$V.size.md"
      :onOk="handleSubmit"
      :onCancel="handleClose"
      :okText="modalType === 'create' ? $t('createText') : $t('updateText')"
    >
      <BannerForm :record="record" ref="form" :bannerTypes="bannerTypes" />
    </Modal>
  </el-card>
</template>

<script>
import {
  getBannerList,
  createBanner,
  updateBanner,
  deleteBanner,
  getBannerTypeList,
  onlineBanner,
  offlineBanner,
  getBannerById,
  getCouponByIds,
  getFreshGoodsByIds,
  getFreshClassifyByIds,
  getMaintenanceClassifyByIds,
  getMaintenanceGoodsByIds
} from '@/api'

/* components
---------------------------------------------------------------- */
import BannerForm from './components/BannerForm'
import { Query, Emitter } from '@/mixins'

/* model
---------------------------------------------------------------- */
import { primaryKey } from './model'
import { bannerResourceTypeEnum } from '@/core/enum'

export default {
  componentName: 'Banners',
  mixins: [Query('query'), Emitter],

  data () {
    return {
      showTip: false,
      total: 0,
      dataSource: [],
      loading: false,
      columns: [
        { prop: 'bannerName', label: '图名称' },
        {
          prop: 'bannerLocation',
          label: '图预览',
          formatter: (row) => {
            const imgSrc = this.$V.staticBaseURL + row['bannerLocation']
            return (
              <el-image
                class="row-img"
                src={imgSrc}
                preview-src-list={[imgSrc]}
              ></el-image>
            )
          }
        },
        { prop: 'bannerSummary', label: '图简介' },
        { prop: 'bannerTypeValue', label: '图类型' },
        {
          prop: 'bannerStateValue',
          label: '状态',
          formatter: (row) => {
            return (
              <el-link
                type={row.bannerState === 1 ? 'primary' : 'danger'}
                onClick={() => this.toggleOnline(row.bannerState !== 1, row)}
              >
                {row.bannerStateValue}
              </el-link>
            )
          }
        },
        {
          prop: 'bannerCreateTime',
          label: '创建时间',
          width: this.$V.cellSize.date,
          formatter: (row) => this.$formatTime(row['bannerCreateTime'])
        },
        { prop: 'bannerCreateUserName', label: '创建人' },
        {
          prop: 'bannerUpdateTime',
          label: '修改时间',
          width: this.$V.cellSize.date,
          formatter: (row) => this.$formatTime(row['bannerUpdateTime'])
        },
        { prop: 'bannerUpdateUserName', label: '修改人' },
        {
          label: '操作',
          minWidth: this.$V.cellSize.action,

          formatter: this.getActionDecorator([
            {
              icon: 'el-icon-edit',
              action: this.onClickUpdate,
              auth: this.$P.business.banners.update,
              type: 'primary'
            },
            {
              icon: 'el-icon-delete',
              action: this.onClickDelete,
              auth: this.$P.business.banners.delete,
              type: 'danger'
            }
          ])
        }
      ],
      record: {},

      bannerTypes: [],

      // -------- Modal ----------
      visible: false,
      modalLoading: false,
      modalType: ''
      // -------- !Modal ----------
    }
  },
  methods: {
    // Requests
    // ------------------------------------------
    getBannerTypeList () {
      if (this.bannerTypes.length) {
        return Promise.resolve()
      }
      return this.Catch(getBannerTypeList, {
        onOk ({ data }) {
          this.bannerTypes = data.map((it) => {
            return {
              label: it.name,
              value: this.$toNumber(it.code)
            }
          })
        }
      })('loading')
    },

    getBannerList (fn) {
      return this.Catch(getBannerList, {
        onOk (res) {
          this.dataSource = res.data.data
          this.total = res.data.total
        }
      })('loading', (fn || this.$noop)(this.query))
    },

    getBannerById (id, { onOk, onError }) {
      return this.Catch(getBannerById, {
        onOk,
        onError
      })('loading', id)
    },

    deleteBanner (id, { onOk }) {
      return this.Catch(deleteBanner, {
        onOk
      })(null, id)
    },

    createBanner (data) {
      return this.Catch(createBanner, {
        onOk () {
          this.$message.success(this.$t('createOk'))
          this.getBannerList()
          this.visible = false
        },
        onError (err) {
          console.log(err)
        }
      })('modalLoading', data)
    },

    updateBanner (id, data) {
      return this.Catch(updateBanner, {
        onOk () {
          this.$message.success(this.$t('updateOk'))
          this.getBannerList()
          this.visible = false
        }
      })('modalLoading', id, data)
    },

    onlineBanner (id) {
      return this.Catch(onlineBanner, {
        onOk () {
          this.$message.success('上线成功')
          this.getBannerList()
        }
      })(null, id)
    },

    offlineBanner (id) {
      return this.Catch(offlineBanner, {
        onOk () {
          this.$message.success('下线成功')
          this.getBannerList()
        }
      })(null, id)
    },

    getCouponByIds (ids, { onOk, onError }) {
      return this.Catch(getCouponByIds, {
        onOk,
        onError
      })('loading', ids)
    },

    getFreshGoodsByIds (ids, { onOk, onError }) {
      return this.Catch(getFreshGoodsByIds, {
        onOk,
        onError
      })('loading', ids)
    },
    getFreshClassifyByIds (ids, { onOk, onError }) {
      return this.Catch(getFreshClassifyByIds, {
        onOk,
        onError
      })('loading', ids)
    },
    getMaintenanceGoodsByIds (ids, { onOk, onError }) {
      return this.Catch(getMaintenanceGoodsByIds, {
        onOk,
        onError
      })('loading', ids)
    },
    getMaintenanceClassifyByIds (ids, { onOk, onError }) {
      return this.Catch(getMaintenanceClassifyByIds, {
        onOk,
        onError
      })('loading', ids)
    },
    // Table
    // ------------------------------------------

    toggleOnline (willOnline, row) {
      this.ConfirmToggleOnline({
        online: willOnline,
        onOk: () =>
          willOnline
            ? this.onlineBanner(row[primaryKey])
            : this.offlineBanner(row[primaryKey])
      })
    },

    ensureTypes () {
      return this.getBannerTypeList()
    },

    onClickDelete (row) {
      this.ConfirmDelete({
        onOk: () =>
          this.deleteBanner(row[primaryKey], {
            onOk () {
              this.$message.success(this.$t('deleteOk'))
              this.getBannerList()
            }
          })
      })
    },

    async onClickUpdate (row) {
      const openModal = (data) => {
        this.record = data
        this.visible = true
      }
      await this.ensureTypes()

      this.getBannerById(row[primaryKey], {
        onOk ({ data }) {
          this.modalType = 'update'
          // 上次选中的商品主键
          if (data.bannerResource) {
            let request

            switch (data.bannerResourceType) {
              case bannerResourceTypeEnum.fresh:
                request = this.getFreshGoodsByIds
                break

              case bannerResourceTypeEnum.maintenance:
                request = this.getMaintenanceGoodsByIds
                break

              case bannerResourceTypeEnum.freshCategory:
                request = this.getFreshClassifyByIds
                break

              case bannerResourceTypeEnum.maintenanceCategory:
                request = this.getMaintenanceGoodsByIds
                break

              case bannerResourceTypeEnum.coupon:
                request = this.getCouponByIds
                break
            }

            request(data.bannerResource, {
              onOk (res) {
                openModal({
                  ...data,
                  bannerResourceList: res.data
                })
              }
            })
          } else {
            openModal(data)
          }
        }
      })
    },

    async onClickCreate () {
      await this.ensureTypes()

      this.modalType = 'create'
      this.record = {}
      this.visible = true
    },

    // Modal
    // ------------------------------------------
    handleSubmit () {
      this.$refs.form.submit((valid, values) => {
        if (valid) {
          if (this.modalType === 'create') {
            this.createBanner(values)
          } else {
            this.updateBanner(values[primaryKey], values)
          }
        }
      })
    },

    // 关闭modal清理数据
    handleClose () {
      this.visible = false
    }
  },
  computed: {
    modalTitle () {
      return this.modalType === 'create'
        ? this.$t('createText')
        : this.$t('updateText')
    }
  },
  components: { BannerForm },

  created () {
    this.getBannerList()

    this.inject(this.getBannerList)

    this.$on('picker.open', this.openPicker)

    this.$nextTick(() => (this.showTip = true))
  }
}
</script>
